package com.zb.api.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.BiConsumer;

/**
 * Mybatis 批量新增工具类
 */
@Slf4j
@Component
public class BatchInsertUtil {

    @Autowired
    SqlSessionFactory sqlSessionFactory;

    /**
     * 批量新增方法
     *
     * @param list       要新增的集合
     * @param clazz      Mapper类
     * @param biConsumer 对应的单条新增方法
     * @param <M>        mapper类型
     * @param <T>        结合元素类型
     */
    public static   <M, T> void batchInsert(List<T> list, Class<M> clazz, BiConsumer<M, T> biConsumer) {
        if (list == null || list.size() == 0) {
            log.info("批量新增列表为空!");
            return;
        }
        SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        try {
            M mapper = session.getMapper(clazz);

            for (int i = 0 ; i < list.size() ; i++){
                biConsumer.accept(mapper, list.get(i));
                if(i%5000==4999){//每5000条提交一次防止内存溢出   提交后无法回滚
                    session.commit();
                    session.clearCache();
                }
            }

            session.commit();
            session.clearCache();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批量新增异常！clazz={}", clazz.getName(), e);
            session.rollback();
        } finally {
            session.close();
        }
    }

}

